const get = require('lodash.get');
function getUpper(scope, name) {
  if (!scope) {
    return null;
  }
  return scope.set.get(name) || getUpper(scope.upper, name);
}

function isBricksVar(scope, name) {
  const variable = getUpper(scope, name);
  if (!variable || !variable.defs[0]) {
    return false;
  }
  const checkboxNode = variable.defs[0].node;
  return get(checkboxNode, 'parent.source.value') === '@dui/ui';
}

module.exports = {
  meta: {
    title: 'bricks-checkbox-prefer-label',
    docs: {
      description: '使用<Checkbox label="xx" />替代<Checkbox title="xx" />',
    },
    fixable: 'code',
    schema: [],
  },
  create(context) {
    return {
      JSXOpeningElement(node) {
        if (node.name.name === 'Checkbox') {
          const scope = context.getScope();
          if (!isBricksVar(scope, 'Checkbox')) {
            return;
          }
          node.attributes.forEach(attr => {
            if (attr.name.name === 'title') {
              context.report({
                node: attr.name,
                message: '请使用label替代title',
                fix(fixer) {
                  return fixer.replaceText(attr.name, 'label');
                },
              });
            }
          });
        }
      },
    };
  },
};
